<?php

namespace app\api\controller\xykeep;

use app\api\model\xykeep\Store as storeModel;
use app\common\controller\Api;
use app\api\model\xykeep\Config;
use app\admin\model\xykeep\store\Banner;
use app\common\model\Area;
use think\Cache;
use think\Config as thinkConfig;
use think\Db;
use think\Queue;

/**
 * 通用接口
 */
class Common extends Api
{
	protected $noNeedLogin = ['*'];
	protected $noNeedRight = ['*'];


	/**
	 * 加载目标信息和通用配置
	 */
	public function init()
	{
        $siteConfig = [];

        $siteConfig['pop_title'] = thinkConfig::get('site.pop_title');
        $siteConfig['pop_tit'] = thinkConfig::get('site.pop_tit');
        $siteConfig['pop_desc'] = thinkConfig::get('site.pop_desc');
        $siteConfig['pop_but'] = thinkConfig::get('site.pop_but');
        $siteConfig['mental_health'] = thinkConfig::get('site.mental_health');
        $siteConfig['teacher_banner'] = thinkConfig::get('site.teacher_banner');
        $siteConfig['travel_title'] = thinkConfig::get('site.travel_title');
        $siteConfig['products_title'] = thinkConfig::get('site.products_title');
        $siteConfig['specail_title'] = thinkConfig::get('site.specail_title');
        $siteConfig['feedback'] = thinkConfig::get('site.feedback');


        $shareConfig = [];
        $shareConfig['title'] = thinkConfig::get('site.share_title');
        $shareConfig['image'] = thinkConfig::get('site.share_image');

        $tabConfig = [];
        $tabConfig['tab_index_tit'] = thinkConfig::get('site.tab_index_tit');
        $tabConfig['tab_course_tit'] = thinkConfig::get('site.tab_course_tit');
        $tabConfig['tab_shop_tit'] = thinkConfig::get('site.tab_shop_tit');
        $tabConfig['tab_my_tit'] = thinkConfig::get('site.tab_my_tit');

        $appConfig = [];
        $appConfig['domain'] = thinkConfig::get('site.domain');
        $appConfig['name'] = thinkConfig::get('site.site_name');
        $appConfig['logo'] = thinkConfig::get('site.logo');
        $appConfig['appmodel'] = thinkConfig::get('site.cheat_audit');
        $appConfig['hide_my'] = thinkConfig::get('site.hide_my');
        $appConfig['hide_index_menu'] = thinkConfig::get('site.hide_index_menu');
        $appConfig['useravatar'] = '/assets/addons/xykeep/imgs/avatar.png';
        $appConfig['balance_on'] = thinkConfig::get('site.balance_on');
        $appConfig['distribution_on'] = thinkConfig::get('site.distribution_on');
		$this->success('init', [
            "siteConfig" => $siteConfig,
			"appConfig" => $appConfig,
			"shareConfig" => $shareConfig,
            "tabConfig" => $tabConfig,
		]);
	}

	/**
     * 根据经纬度获取城市数据
     *
     * @param string $lng     经度
     * @param string $lat     纬度
     */
    public function cityData()
    {
		$lng = $this->request->request('lng');
		$lat = $this->request->request('lat');

		// 添加缓存标记，避免重复执行
		$level = 3;
        if (Cache::tag('geo')->get('geo:area_level_' . $level) !== true) {
            self::area2RedisGeo($level);
        }
		$this->success('城市信息', Area::getCityFromLngLat($lng, $lat));
    }

	/**
     * 区域经纬度到redis
    */
    private function area2RedisGeo($level) {
        $areas = Area::where(['level' => $level])->select();
        $namearr = [1 => 'geo:province', 2 => 'geo:city', 3 => 'geo:district'];
        $redis = Cache::store('redis')->handler();
        foreach ($areas as $area) {
            if (method_exists($redis, 'geoadd')) {
                $redis->geoadd($namearr[$area['level']], $area['lng'], $area['lat'], $area['id']);
            }
        }
        Cache::tag('geo')->set('geo:area_level_' . $level, true);
    }

	/**
	 * 省市区
	 */
	public function area()
    {
        $data['provinceData'] = Area::where('level', 1)->order('id asc')->field('id as value, name as label, pid, level')->select();
        foreach ($data['provinceData'] as $k => $p) {
            $data['cityData'][$k] = Area::where(['level' => 2, 'pid' => $p->value])->order('id asc')->field('id as value, name as label, pid, level')->select();
            foreach ($data['cityData'][$k] as $i => $c) {
                $data['areaData'][$k][$i] = Area::where(['level' => 3, 'pid' => $c->value])->order('id asc')->field('id as value, name as label, pid, level')->select();
            }
        }

        $this->success('省市区', $data);

    }

    /**
     * 获取门店信息配置
     */
    public function get_index_config()
    {
        $configModel = new \think\Config();
        $configs = [];
        $configs['store_info'] = $configModel::get('site.store_info');
        $configs['store_tel'] = $configModel::get('site.store_tel');
        $configs['store_addr'] = $configModel::get('site.store_addr');
        $configs['store_times'] = $configModel::get('site.store_times');
        $configs['store4_desc'] = $configModel::get('site.store4_desc');
        $configs['store4_trainer'] = $configModel::get('site.store4_trainer');
        $configs['store1_brand'] = $configModel::get('site.store1_brand');
        $configs['store1_desc'] = $configModel::get('site.store1_desc');
        $configs['store5_desc'] = $configModel::get('site.store5_desc');

        //首页营销
        $where = [
            //这段代码如果开启，就不会是完整的数组就会报错
//            'status' => 'normal',
        ];
        $data = storeModel::where($where)->order('id asc')->select();

        $store_banner = [];
        $store_banner[0] = [];
        foreach ($data as $item) {
            $store_banner[] = Banner::where(['store_id'=>$item['id']])->select();
            //最好是普通数组，把对象类型强制改成数组
            if($item['id']==8){for ($i=9;$i<24;$i++){$store_banner[] = [];}}
        }

        $this->success('获取成功',['configs'=>$configs,'store_banner'=>$store_banner]);
    }

    /**
     * 定期检查课包到期情况，发现发微信模板消息给用户
     */
    public function check_timeout()
    {

        $vipWhere = [];
        $sevenStarttime = time() + 86400 * 7;
        $sevenEndtime = time() + 86400 * 8;
        $vipWhere['overdue_time'] = ['between',[$sevenStarttime,$sevenEndtime]];
        $vipList = Db::name('xykeep_user_vip')->where($vipWhere)->select();
        foreach ($vipList as $item) {
            $msg = [
                'user_id' => $item['user_id'],
                'name' => $item['type']=='nums'?'课包（次卡）':'课包（时长卡）',
                'left' => $item['type']=='nums'?$item['nums'].'次':'7天时长',
                'overdue_time' => $item['overdue_time']
            ];
            Queue::later(10, '\addons\xykeep\job\Order@vipTimeout', $msg, 'XYkeep');
        }

        $this->success('定期检查课包到期情况');
    }
}
